﻿ #region Disclaimer/Info
 
 /////////////////////////////////////////////////////////////////////////////////////////////////
 //
 //   File:		PostRepository.cs
 //   Website:		http://dexterblogengine.com/
 //   Authors:		http://dexterblogengine.com/About.ashx
 //   Rev:		1
 //   Created:		19/01/2011
 //   Last edit:		19/01/2011
 //   License:		GNU Library General Public License (LGPL)
 //   File:            PostRepository.cs
 //   For updated news and information please visit http://dexterblogengine.com/
 //   Dexter is hosted to Codeplex at http://dexterblogengine.codeplex.com
 //   For any question contact info@dexterblogengine.com
 //
 ///////////////////////////////////////////////////////////////////////////////////////////////////
 
 #endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Dexter.Core.Data.Repository;
using Dexter.Domain.Model;
using Dexter.Domain.Results;
using Dexter.Logger.Contracts;
using Dexter.Repository.NHibernate.Queries;
using NHibernate;
using NHibernate.Criterion;
using NHibernate.Transform;
using Topics.Radical.Validation;
using ISessionFactory = Dexter.Repository.NHibernate.SessionFactory.ISessionFactory;

namespace Dexter.Repository.NHibernate.Repositories {
	/// <summary>
	/// The implementation of <see cref="IPostRepository"/>.
	/// </summary>
	/// <example>The following is an example of initializing 
	///          an <c>PostRepository</c> type:
	///   <code>
	///       // Create the type.
	///       PostRepository ds = new PostRepository;
	/// 
	///       if ( null == ds )
	///           return;
	/// 
	///       return ds.DoSomething( 5 );
	///   </code>
	/// </example>
	public class PostRepository : RepositoryBase <Post> , IPostRepository {
		/// <summary>
		/// Initializes a new instance of the <see cref="PostRepository"/> class.
		/// </summary>
		/// <param name="sessionFactory">The session factory.</param>
		/// <param name="logger">The logger.</param>
		public PostRepository ( ISessionFactory sessionFactory , ILogger logger ) : base ( sessionFactory , logger ) {}

		#region IPostRepository Members

		/// <summary>
		/// Retireve a paged list of approved posts.
		/// </summary>
		/// <param name="pageIndex">Index of the page (0 based).</param>
		/// <param name="pageSize">The number of items to retrieve.</param>
		/// <returns>
		/// An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException">Will be throw if the page size will be lesser than 0.</exception>
		/// <exception cref="ArgumentOutOfRangeException">Will be throw if the page index will be lesser than 1.</exception>
		public virtual IPagedResult<Post> GetPublished ( int pageIndex, int pageSize ) {
			return GetPublished ( pageIndex , pageSize , false );
		}

		/// <summary>
		/// Retireve a paged list of approved posts.
		/// </summary>
		/// <param name="pageIndex">Index of the page (0 based).</param>
		/// <param name="pageSize">The number of items to retrieve.</param>
		/// <param name="includeFuturesPosts">if set to <c>true</c> the result will include the futures posts.</param>
		/// <returns>
		/// An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		public virtual IPagedResult<Post> GetPublished ( int pageIndex, int pageSize, bool includeFuturesPosts ) {
			return GetPublished ( pageIndex , pageSize , includeFuturesPosts , true );
		}

		/// <summary>
		/// Retireve a paged list of approved posts.
		/// </summary>
		/// <param name="pageIndex">Index of the page (0 based).</param>
		/// <param name="pageSize">The number of items to retrieve.</param>
		/// <param name="includeFuturesPosts">if set to <c>true</c> the result will include the futures posts.</param>
		/// <param name="enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		/// <returns>
		/// An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		public virtual IPagedResult<Post> GetPublished ( int pageIndex, int pageSize, bool includeFuturesPosts, bool enableTracking ) {
			Ensure.That ( pageIndex )
				.Named ( "pageIndex" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 0 , Or.Equal )
				.WithMessage ( "Invalid page index." );

			Ensure.That ( pageSize )
				.Named ( "pageSize" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 0 )
				.WithMessage ( "Invalid page size." );


			IFutureValue <long> total = Session.GetNamedQuery ( KnownQueries.PostRepository.GetPublishedCount )
				.SetParameter("publishDate", !includeFuturesPosts
													? DateTime.Now
													: DateTime.Now.AddYears(1000))
				.FutureValue <long> ( );

			var detached = QueryOver.Of<Post> ( )
				.Where ( x => x.IsPublished && x.PublishDate < ( !includeFuturesPosts ? DateTime.Now : DateTime.Now.AddYears ( 1000 ) ) )
				.OrderBy ( x => x.PublishDate ).Desc
				.Select ( x => x.Id )
				.Take ( pageSize )
				.Skip ( pageIndex * pageSize );

			IEnumerable<Post> result = Session.QueryOver<Post>()
				.WithSubquery.WhereProperty(x => x.Id).In(detached)
				.OrderBy(x => x.PublishDate).Desc
				.Fetch(x => x.Tags).Eager
				.Left.JoinQueryOver(x => x.Categories)
				.TransformUsing(Transformers.DistinctRootEntity)
				.Future<Post>();

			return new PagedResult <Post> ( pageIndex , pageSize , result.ToList ( ) , total.Value );
		}

		/// <summary>
		/// Gets the unpublished.
		/// </summary>
		/// <param name="pageIndex">Index of the page.</param>
		/// <param name="pageSize">Size of the page.</param>
		/// <returns></returns>
		public virtual IPagedResult<Post> GetUnpublished ( int pageIndex, int pageSize ) {
			return GetUnpublished ( pageIndex , pageSize , false );
		}

		/// <summary>
		/// Retireve a paged list of unapproved posts.
		/// </summary>
		/// <param name="pageIndex">Index of the page (0 based).</param>
		/// <param name="pageSize">The number of items to retrieve.</param>
		/// <param name="includeFuturesPosts">if set to <c>true</c> the result will include the futures posts.</param>
		/// <returns>
		/// An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		public virtual IPagedResult<Post> GetUnpublished ( int pageIndex, int pageSize, bool includeFuturesPosts ) {
			return GetUnpublished(pageIndex, pageSize, includeFuturesPosts, true);
		}

		/// <summary>
		/// Retireve a paged list of unapproved posts.
		/// </summary>
		/// <param name="pageIndex">Index of the page (0 based).</param>
		/// <param name="pageSize">The number of items to retrieve.</param>
		/// <param name="includeFuturesPosts">if set to <c>true</c> the result will include the futures posts.</param>
		/// <param name="enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		/// <returns>
		/// An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		public virtual IPagedResult<Post> GetUnpublished ( int pageIndex, int pageSize, bool includeFuturesPosts, bool enableTracking ) {
			Ensure.That ( pageIndex )
				.Named ( "pageIndex" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 0 , Or.Equal )
				.WithMessage ( "Invalid page index." );

			Ensure.That ( pageSize )
				.Named ( "pageSize" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 0 )
				.WithMessage ( "Invalid page size." );

			IFutureValue <long> total = Session.GetNamedQuery ( KnownQueries.PostRepository.GetUnpublishedCount )
				.SetParameter("publishDate", !includeFuturesPosts
													? DateTime.Now
													: DateTime.Now.AddYears(1000))
				.SetFirstResult(pageIndex * pageSize)
				.FutureValue <long> ( );

			var detached = QueryOver.Of<Post> ( )
				.Where(x => x.IsPublished == false)
				.Where ( x => x.PublishDate < ( !includeFuturesPosts ? DateTime.Now : DateTime.Now.AddYears ( 1000 ) ) )
				.OrderBy ( x => x.PublishDate ).Desc
				.Select ( x => x.Id )
				.Take ( pageSize )
				.Skip ( pageIndex * pageSize );

			IEnumerable<Post> result = Session.QueryOver<Post> ( )
				.WithSubquery.WhereProperty ( x => x.Id ).In ( detached )
				.Fetch ( x => x.Tags ).Eager
				.TransformUsing ( Transformers.DistinctRootEntity )
				.Future<Post> ( );

			return new PagedResult <Post> ( pageIndex , pageSize , result.ToList ( ) , total.Value );
		}

		/// <summary>
		/// Retireve a paged list of unapproved posts with <see cref="Item.PublishDate"/> equal to <paramref name="date"/>.
		/// </summary>
		/// <param name="pageIndex">Index of the page (0 based).</param>
		/// <param name="pageSize">The number of items to retrieve.</param>
		/// <param name="date">The date.</param>
		/// <returns>
		/// An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		public virtual IPagedResult<Post> GetUnpublishedForTheSpecifiedDate ( int pageIndex, int pageSize, DateTime date ) {
			return GetUnpublishedForTheSpecifiedDate ( pageIndex , pageSize , date , false );
		}

		/// <summary>
		/// Retireve a paged list of unapproved posts with <see cref="Item.PublishDate"/> equal to <paramref name="date"/>.
		/// </summary>
		/// <param name="pageIndex">Index of the page (0 based).</param>
		/// <param name="pageSize">The number of items to retrieve.</param>
		/// <param name="date">The date.</param>
		/// <param name="enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		/// <returns>
		/// An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		public virtual IPagedResult<Post> GetUnpublishedForTheSpecifiedDate ( int pageIndex, int pageSize, DateTime date, bool enableTracking ) {
			Ensure.That ( pageIndex )
				.Named ( "pageIndex" )
				.WithPreview ( ( v, e ) => Logger.Warn ( v.GetFullErrorMessage ( ), e ) )
				.IsGreaterThen ( 0, Or.Equal )
				.WithMessage ( "Invalid page index." );

			Ensure.That ( pageSize )
				.Named ( "pageSize" )
				.WithPreview ( ( v, e ) => Logger.Warn ( v.GetFullErrorMessage ( ), e ) )
				.IsGreaterThen ( 0 )
				.WithMessage ( "Invalid page size." );

			IFutureValue<long> total = Session.GetNamedQuery ( KnownQueries.PostRepository.GetUnpublishedForTheSpecifiedDateCount )
				.SetParameter(":minDate",date.AddDays ( -1 ))
				.SetParameter(":maxDate",date.AddDays ( 1 ))
				.FutureValue<long> ( );

			IEnumerable<Post> result = Session.GetNamedQuery ( KnownQueries.PostRepository.GetUnpublishedForTheSpecifiedDate )
				.SetParameter ( ":minDate", date.AddDays ( -1 ) )
				.SetParameter ( ":maxDate", date.AddDays ( 1 ) )
				.SetFirstResult ( pageIndex * pageSize )
				.SetMaxResults ( pageSize )
				.SetReadOnly ( !enableTracking )
				.Future<Post> ( );

			return new PagedResult<Post> ( pageIndex, pageSize, result.ToList ( ), total.Value );
		}

		///<summary>
		///	Retireve a paged list of all posts with the property <see cref="Item.CommentEnabled"/> set to <c>false</c>.
		///</summary>
		/// <remarks>
		///		The result will include only published past posts.
		///		Moreover the result hasn't the tracking system enabled
		/// </remarks>
		///<param name = "pageIndex">Index of the page (0 based).</param>
		///<param name = "pageSize">The number of items to retrieve.</param>
		///<returns>An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.</returns>
		///<exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		///<exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		public virtual IPagedResult<Post> GetPublishedPostWithCommentsDisabled ( int pageIndex, int pageSize ) {
			return GetPublishedPostWithCommentsDisabled ( pageIndex , pageSize , false );
		}

		///<summary>
		///	Retireve a paged list of all posts with the property <see cref="Item.CommentEnabled"/> set to <c>false</c>.
		///</summary>
		/// <remarks>
		///		The result will include only published past posts.
		///		Moreover the result hasn't the tracking system enabled
		/// </remarks>
		///<param name = "pageIndex">Index of the page (0 based).</param>
		///<param name = "pageSize">The number of items to retrieve.</param>
		///<param name = "enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		///<returns>An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.</returns>
		///<exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		///<exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		public virtual IPagedResult<Post> GetPublishedPostWithCommentsDisabled ( int pageIndex, int pageSize, bool enableTracking ) {
			Ensure.That ( pageIndex )
				.Named ( "pageIndex" )
				.WithPreview ( ( v, e ) => Logger.Warn ( v.GetFullErrorMessage ( ), e ) )
				.IsGreaterThen ( 0, Or.Equal )
				.WithMessage ( "Invalid page index." );

			Ensure.That ( pageSize )
				.Named ( "pageSize" )
				.WithPreview ( ( v, e ) => Logger.Warn ( v.GetFullErrorMessage ( ), e ) )
				.IsGreaterThen ( 0 )
				.WithMessage ( "Invalid page size." );
			
			throw new NotImplementedException ( );
		}

		/// <summary>
		/// Retireve a paged list of all posts.
		/// </summary>
		/// <param name="pageIndex">Index of the page (0 based).</param>
		/// <param name="pageSize">The number of items to retrieve.</param>
		/// <param name="startDate">The start date.</param>
		/// <param name="endDate">The end date.</param>
		/// <returns>
		/// An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.
		/// </returns>
		/// <remarks>
		/// The result will include only published.
		/// Moreover the result hasn't the tracking system enabled
		/// </remarks>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		public IPagedResult <Post> GetPublishedPostForSpecifiedPublishDateRange ( int pageIndex , int pageSize , DateTime startDate , DateTime endDate ) {
			Ensure.That ( pageIndex )
				.Named ( "pageIndex" )
				.WithPreview ( ( v, e ) => Logger.Warn ( v.GetFullErrorMessage ( ), e ) )
				.IsGreaterThen ( 0, Or.Equal )
				.WithMessage ( "Invalid page index." );

			Ensure.That ( pageSize )
				.Named ( "pageSize" )
				.WithPreview ( ( v, e ) => Logger.Warn ( v.GetFullErrorMessage ( ), e ) )
				.IsGreaterThen ( 0 )
				.WithMessage ( "Invalid page size." );

			IFutureValue<long> total = Session.GetNamedQuery ( KnownQueries.PostRepository.GetPublishedPostForSpecifiedPublishDateRangeCount )
				.SetParameter ( "minDate", startDate )
				.SetParameter ( "maxDate", endDate )
				.FutureValue<long> ( );

			IEnumerable<Post> result = Session.GetNamedQuery ( KnownQueries.PostRepository.GetPublishedPostForSpecifiedPublishDateRange )
				.SetParameter ( "minDate", startDate )
				.SetParameter ( "maxDate", endDate )
				.SetFirstResult ( pageIndex * pageSize )
				.SetMaxResults ( pageSize )
				.SetReadOnly ( true )
				.Future<Post> ( );

			return new PagedResult<Post> ( pageIndex, pageSize, result.ToList ( ), total.Value );
		}

		/// <summary>
		/// Retireve a paged list of posts.
		/// </summary>
		/// <param name="pageIndex">Index of the page (0 based).</param>
		/// <param name="pageSize">The number of items to retrieve.</param>
		/// <returns>
		/// An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		public virtual IPagedResult<Post> GetCompleteList ( int pageIndex, int pageSize ) {
			return GetCompleteList ( pageIndex , pageSize , true );
		}

		/// <summary>
		/// Retireve a paged list of posts.
		/// </summary>
		/// <param name="pageIndex">Index of the page (0 based).</param>
		/// <param name="pageSize">The number of items to retrieve.</param>
		/// <param name="enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		/// <returns>
		/// An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		public virtual IPagedResult<Post> GetCompleteList ( int pageIndex, int pageSize, bool enableTracking ) {
			Ensure.That ( pageIndex )
				.Named ( "pageIndex" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 0 , Or.Equal )
				.WithMessage ( "Invalid page index." );

			Ensure.That ( pageSize )
				.Named ( "pageSize" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 0 )
				.WithMessage ( "Invalid page size." );

			IFutureValue <long> total = Session.GetNamedQuery ( KnownQueries.PostRepository.GetCompleteListCount )
				.FutureValue <long> ( );

			IEnumerable <Post> result = Session.GetNamedQuery ( KnownQueries.PostRepository.GetCompleteList )
				.SetFirstResult ( pageIndex * pageSize )
				.SetMaxResults ( pageSize )
				.SetReadOnly ( !enableTracking )
				.Future <Post> ( );

			return new PagedResult <Post> ( pageIndex , pageSize , result.ToList ( ) , total.Value );
		}

		/// <summary>
		/// Return a list of posts for a specified month.
		/// </summary>
		/// <param name="month">The id of the month (1 for january, 2 for february, etc).</param>
		/// <param name="year">The year (2010, 1978, etc).</param>
		/// <param name="pageIndex">Index of the page (0 based).</param>
		/// <param name="pageSize">The number of items to retrieve.</param>
		/// <returns>
		/// An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="month"/> is not between 1 and 12.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="year"/> is lesser than 1400.</exception>
		public virtual IPagedResult<Post> GetByMonth ( int month, int year, int pageIndex, int pageSize ) {
			return GetByMonth ( month , year , pageIndex , pageSize , true );
		}

		/// <summary>
		/// Return a list of posts for a specified month.
		/// </summary>
		/// <param name="month">The id of the month (1 for january, 2 for february, etc).</param>
		/// <param name="year">The year (2010, 1978, etc).</param>
		/// <param name="pageIndex">Index of the page (0 based).</param>
		/// <param name="pageSize">The number of items to retrieve.</param>
		/// <param name="onlyPublished">if set to <c>true</c> the resul will be included only the published posts.</param>
		/// <returns>
		/// An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="month"/> is not between 1 and 12.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="year"/> is lesser than 1400.</exception>
		public virtual IPagedResult<Post> GetByMonth ( int month, int year, int pageIndex, int pageSize, bool onlyPublished ) {
			return GetByMonth(month, year, pageIndex, pageSize, onlyPublished, true);
		}

		/// <summary>
		/// Return a list of posts for a specified month.
		/// </summary>
		/// <param name="month">The id of the month (1 for january, 2 for february, etc).</param>
		/// <param name="year">The year (2010, 1978, etc).</param>
		/// <param name="pageIndex">Index of the page (0 based).</param>
		/// <param name="pageSize">The number of items to retrieve.</param>
		/// <param name="onlyPublished">if set to <c>true</c> the resul will be included only the published posts.</param>
		/// <param name="enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		/// <returns>
		/// An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="month"/> is not between 1 and 12.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="year"/> is lesser than 1400.</exception>
		public virtual IPagedResult<Post> GetByMonth ( int month, int year, int pageIndex, int pageSize, bool onlyPublished, bool enableTracking ) {
			Ensure.That ( pageIndex )
				.Named ( "pageIndex" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 0 , Or.Equal )
				.WithMessage ( "Invalid page index." );

			Ensure.That ( pageSize )
				.Named ( "pageSize" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 0 )
				.WithMessage ( "Invalid page size." );

			Ensure.That ( month )
				.Named ( "month" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsWithin ( 1 , 12 , Boundary.IncludeBounds )
				.WithMessage ( "Invalid month. It should be within 1 and 12." );

			Ensure.That ( year )
				.Named ( "year" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 1399 )
				.WithMessage ( "Invalid year. It should be greather then 1400" );


			IFutureValue<long> total = Session.GetNamedQuery(KnownQueries.PostRepository.GetByMonthCount)
				.SetParameter("month", month)
				.SetParameter("year", year)
				.SetFirstResult(pageIndex * pageSize)
				.FutureValue<long>();

			IEnumerable<Post> result = Session.GetNamedQuery(KnownQueries.PostRepository.GetByMonth)
				.SetParameter("month",month)
				.SetParameter("year", year)
				.SetFirstResult(pageIndex * pageSize)
				.SetMaxResults(pageSize)
				.SetReadOnly(!enableTracking)
				.Future<Post>();

			return new PagedResult<Post>(pageIndex, pageSize, result.ToList(), total.Value);
		}

		/// <summary>
		/// Return a list approved posts, sorted by publish date.
		/// </summary>
		/// <param name="numberOfItems">The number of items.</param>
		/// <param name="includeFutures">if set to <c>true</c> the resulset includes the futures posts.</param>
		/// <returns>
		/// Return a list of <see cref="Post"/>.
		/// The return item could be null if there isn't items into the repository.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="numberOfItems"/> is lesser than 1.</exception>
		public virtual IEnumerable<Post> GetRecent ( int numberOfItems, bool includeFutures ) {
			return GetRecent ( numberOfItems , includeFutures , true );
		}

		/// <summary>
		/// Return a list approved posts, sorted by publish date.
		/// </summary>
		/// <param name="numberOfItems">The number of items.</param>
		/// <param name="includeFutures">if set to <c>true</c> the resulset includes the futures posts.</param>
		/// <param name="enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		/// <returns>
		/// Return a list of <see cref="Post"/>.
		/// The return item could be null if there isn't items into the repository.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="numberOfItems"/> is lesser than 1.</exception>
		public virtual IEnumerable<Post> GetRecent ( int numberOfItems, bool includeFutures, bool enableTracking ) {
			Ensure.That ( numberOfItems )
				.Named ( "numberOfItems" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 1 )
				.WithMessage ( "Invalid numberOfItems. It should be greather then 1" );

			IEnumerable <Post> result = Session.GetNamedQuery ( KnownQueries.PostRepository.GetRecent )
				.SetParameter ( "publishDate" , !includeFutures
				                                	? DateTime.Now
													: DateTime.Now.AddYears ( 1000 ) )
				.SetMaxResults ( numberOfItems )
				.SetReadOnly ( !enableTracking )
				.List <Post> ( );

			return result;
		}

		/// <summary>
		/// Return a list most comment posts, sorted by publish date.
		/// </summary>
		/// <param name="pageIndex">Index of the page (0 based).</param>
		/// <param name="pageSize">The number of items to retrieve.</param>
		/// <returns>
		/// An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		public virtual IPagedResult<Post> GetMostComment ( int pageIndex, int pageSize ) {
			return GetMostComment ( pageIndex , pageSize , true );
		}

		/// <summary>
		/// Return a list most comment posts, sorted by publish date.
		/// </summary>
		/// <param name="pageIndex">Index of the page (0 based).</param>
		/// <param name="pageSize">The number of items to retrieve.</param>
		/// <param name="enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		/// <returns>
		/// An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		public virtual IPagedResult<Post> GetMostComment ( int pageIndex, int pageSize, bool enableTracking ) {
			Ensure.That ( pageIndex )
				.Named ( "pageIndex" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 0 , Or.Equal )
				.WithMessage ( "Invalid page index." );

			Ensure.That ( pageSize )
				.Named ( "pageSize" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 0 )
				.WithMessage ( "Invalid page size." );

			IFutureValue<long> total = Session.GetNamedQuery(KnownQueries.PostRepository.GetMostCommentCount)
				.SetFirstResult(pageIndex * pageSize)
				.FutureValue<long>();

			IEnumerable<Post> result = Session.GetNamedQuery(KnownQueries.PostRepository.GetMostComment)
				.SetFirstResult(pageIndex * pageSize)
				.SetMaxResults(pageSize)
				.SetReadOnly(!enableTracking)
				.Future<Post>();

			return new PagedResult<Post>(pageIndex, pageSize, result.ToList(), total.Value);
		}

		/// <summary>
		/// Return a list of posts for a specified category, sorted by publish date.
		/// </summary>
		/// <param name="categoryId">The category Id.</param>
		/// <param name="pageIndex">Index of the page (0 based).</param>
		/// <param name="pageSize">The number of items to retrieve.</param>
		/// <returns>
		/// An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		public virtual IPagedResult<Post> GetByCategory ( int categoryId, int pageIndex, int pageSize ) {
			return GetByCategory ( categoryId , pageIndex , pageSize , true );
		}

		/// <summary>
		/// Return a list of posts for a specified category, sorted by publish date.
		/// </summary>
		/// <param name="categoryId">The category Id.</param>
		/// <param name="pageIndex">Index of the page (0 based).</param>
		/// <param name="pageSize">The number of items to retrieve.</param>
		/// <param name="enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		/// <returns>
		/// An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		public virtual IPagedResult<Post> GetByCategory ( int categoryId, int pageIndex, int pageSize, bool enableTracking ) {
			Ensure.That ( pageIndex )
				.Named ( "pageIndex" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 0 , Or.Equal )
				.WithMessage ( "Invalid page index." );

			Ensure.That ( pageSize )
				.Named ( "pageSize" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 0 )
				.WithMessage ( "Invalid page size." );

			Ensure.That ( categoryId )
				.Named ( "categoryId" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 0 )
				.WithMessage ( "Invalid category id." );

			var category = Session.GetNamedQuery ( KnownQueries.CategoryRepository.GetCategoryByKeyWithChilds )
				.SetParameter ( "id" , categoryId )
				.UniqueResult <Category> ( );

			if(category == null)
				throw new ArgumentOutOfRangeException ( "categoryId" , "Invalid category id." );

			var flatTree = category.Categories.ToFlat ( x => x.Categories ).Select ( x => x.Id );

			var categoriesId = new List <int> ( );
			
			categoriesId.Add ( categoryId );
			categoriesId.AddRange ( flatTree );

			string hql = string.Format("select distinct p from Post p inner join fetch p.Categories cat where cat.Id in ({0}) order by p.PublishDate desc", string.Join(",", categoriesId));
			string hqlCount = string.Format ( "select Count(distinct p.Id) from Post p inner join p.Categories cat where cat.Id in ({0})", string.Join ( ",", categoriesId ) );

			IFutureValue<long> total = Session.CreateQuery ( hqlCount )
				.FutureValue<long> ( );

			IEnumerable<Post> result = Session.CreateQuery ( hql )
				.SetFirstResult ( pageIndex * pageSize )
				.SetMaxResults ( pageSize )
				.SetReadOnly ( !enableTracking )
				.Future<Post> ( );

			return new PagedResult<Post> ( pageIndex, pageSize, result.ToList ( ), total.Value );
		}

		/// <summary>
		/// Gets the by author.
		/// </summary>
		/// <param name="author">The author.</param>
		/// <param name="pageIndex">Index of the page (0 based).</param>
		/// <param name="pageSize">The number of items to retrieve.</param>
		/// <returns>
		/// An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="author"/> is <c>null</c> or <c>empty</c>.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		public virtual IPagedResult<Post> GetByAuthor ( string author, int pageIndex, int pageSize ) {
			return GetByAuthor ( author , pageIndex , pageSize , true );
		}

		/// <summary>
		/// Gets the by author.
		/// </summary>
		/// <param name="author">The author.</param>
		/// <param name="pageIndex">Index of the page (0 based).</param>
		/// <param name="pageSize">The number of items to retrieve.</param>
		/// <param name="enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		/// <returns>
		/// An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="author"/> is <c>null</c> or <c>empty</c>.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		public virtual IPagedResult<Post> GetByAuthor ( string author, int pageIndex, int pageSize, bool enableTracking ) {
			Ensure.That ( pageIndex )
				.Named ( "pageIndex" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 0 , Or.Equal )
				.WithMessage ( "Invalid page index." );

			Ensure.That ( pageSize )
				.Named ( "pageSize" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 0 )
				.WithMessage ( "Invalid page size." );

			Ensure.That ( author )
				.Named ( "author" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsNotNullNorEmpty ( )
				.WithMessage ( "Invalid post author." );

			throw new NotImplementedException ( );
		}

		/// <summary>
		/// Retrieve a post for a specified slug.
		/// </summary>
		/// <param name="slug">The slug.</param>
		/// <returns>
		/// An instance of <see cref="Post"/>.
		/// It could be null if there isn't an item with the specified slug into the repository.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="slug"/> is <c>null</c> or <c>empty</c>.</exception>
		public virtual Post GetBySlug ( string slug ) {
			return GetBySlug ( slug , true );
		}

		/// <summary>
		/// Retrieve a post for a specified slug.
		/// </summary>
		/// <param name="slug">The slug.</param>
		/// <param name="enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		/// <returns>
		/// An instance of <see cref="Post"/>.
		/// It could be null if there isn't an item with the specified slug into the repository.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="slug"/> is <c>null</c> or <c>empty</c>.</exception>
		public virtual Post GetBySlug ( string slug, bool enableTracking ) {
			Ensure.That ( slug )
				.Named ( "slug" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsNotNullNorEmpty ( )
				.WithMessage ( "Invalid post slug." );

			return Session.GetNamedQuery ( KnownQueries.PostRepository.GetBySlug )
				.SetParameter ( "slug" , slug )
				.SetReadOnly ( !enableTracking )
				.SetResultTransformer(new DistinctRootEntityResultTransformer())
				.UniqueResult <Post> ( );
		}

		/// <summary>
		/// Retrieve a post for a specified key.
		/// </summary>
		/// <param name="key">The key of the post.</param>
		/// <returns>
		/// An instance of <see cref="Post"/>.
		/// It could be null if there isn't an item with the specified key into the repository.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="key"/> is lesser than 1.</exception>
		public virtual Post GetByKey ( int key ) {
			return GetByKey ( key , true );
		}

		/// <summary>
		/// Retrieve a post for a specified key.
		/// </summary>
		/// <param name="key">The key of the post.</param>
		/// <param name="enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		/// <returns>
		/// An instance of <see cref="Post"/>.
		/// It could be null if there isn't an item with the specified key into the repository.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="key"/> is lesser than 1.</exception>
		public virtual Post GetByKey ( int key, bool enableTracking ) {
			Ensure.That ( key )
				.Named ( "key" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 0 )
				.WithMessage ( "Invalid post key." );

			return Session.GetNamedQuery ( KnownQueries.PostRepository.GetByKey )
				.SetParameter ( "id", key )
				.SetReadOnly ( !enableTracking )
				.UniqueResult<Post> ( );
		}

		/// <summary>
		/// 	Deletes the post with the specified slug, from the repository.
		/// </summary>
		/// <param name = "item">The post.</param>
		/// <exception cref="ArgumentNullException">If <paramref name="item"/> is <c>null</c>.</exception>
		public virtual void Delete ( Post item ) {
			Ensure.That ( item )
					.Named ( "item" )
					.WithPreview ( ( v, e ) => Logger.Warn ( v.GetFullErrorMessage ( ), e ) )
					.IsNotNull ( )
					.WithMessage ( "Invalid post." );

			Session.Delete ( item );
		}

		/// <summary>
		/// Saves the specified post into the repository.
		/// </summary>
		/// <param name="item">The item.</param>
		/// <exception cref="ArgumentNullException">If <paramref name="item"/> is <c>null</c>.</exception>
		public virtual void Save ( Post item ) {
			Ensure.That ( item )
				.Named ( "item" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsNotNull ( )
				.WithMessage ( "Invalid post." );

			item.ValidateForPublish (  );

			Session.Save ( item );
		}

		/// <summary>
		/// Updates the specified post into the repository.
		/// </summary>
		/// <param name="item">The item.</param>
		/// <exception cref="ArgumentNullException">If <paramref name="item"/> is <c>null</c>.</exception>
		public virtual void Update ( Post item ) {
			Ensure.That ( item )
				.Named ( "item" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsNotNull ( )
				.WithMessage ( "Invalid post." );

			item.ValidateForUpdate();
			Session.Update(item);
		}

		/// <summary>
		/// Retrieve the list of months for all published posts.
		/// </summary>
		/// <returns>
		/// Return a list of <c>MonthDTO</c> based on <c>PublishDate</c> property of <c>Item</c>.
		/// It could be null if there aren't items into the repository.
		/// </returns>
		public virtual IList<Month> GetMonths()
		{
			return GetMonths ( false );
		}

		/// <summary>
		/// Retrieve the list of months for all posts.
		/// </summary>
		/// <param name="includeFutures">if set to <c>true</c> the result will include the future posts; otherwise, <c>false</c>.</param>
		/// <returns>
		/// Return a list of <c>MonthDTO</c> based on <c>PublishDate</c> property of <c>Item</c>.
		/// It could be null if there aren't items into the repository.
		/// </returns>
		public virtual IList<Month> GetMonths(bool includeFutures)
		{
			return GetMonths ( null , false );
		}

		/// <summary>
		/// Retrieve the list of months for all published posts, filter by an author.
		/// </summary>
		/// <param name="username">The username.</param>
		/// <returns>
		/// Return a list of <c>MonthDTO</c> based on <c>PublishDate</c> property of <c>Item</c>.
		/// It could be null if there aren't items into the repository.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="username"/> is <c>null</c> or <c>empty</c>.</exception>
		public virtual IList<Month> GetMonths(string username)
		{
			return GetMonths ( username , false );
		}

		/// <summary>
		/// Retrieve the list of months for all posts, filter by an author.
		/// </summary>
		/// <param name="username">The username.</param>
		/// <param name="includeFutures">if set to <c>true</c> the result will include the future posts; otherwise, <c>false</c>.</param>
		/// <returns>
		/// Return a list of <c>MonthDTO</c> based on <c>PublishDate</c> property of <c>Item</c>.
		/// It could be null if there aren't items into the repository.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="username"/> is <c>null</c> or <c>empty</c>.</exception>
		public virtual IList<Month> GetMonths(string username, bool includeFutures)
		{
			StringBuilder stringQuery = new StringBuilder ( );

			stringQuery.Append ( "select new Month(count(p.Id), month(p.PublishDate), year(p.PublishDate)) from Post p where 1 = 1 " );

			if (!string.IsNullOrEmpty ( username ))
				stringQuery.Append ( " and p.Username = :username " );

			if (!includeFutures)
				stringQuery.Append ( " and p.PublishDate < :publishDate" );

			stringQuery.Append ( " group by year(p.PublishDate), month(p.PublishDate) order by year(p.PublishDate) desc, month(p.PublishDate) desc" );

			IQuery query = Session.CreateQuery ( stringQuery.ToString ( ) );

			if (!string.IsNullOrEmpty ( username ))
				query.SetParameter ( "username", username );

			if (!includeFutures)
				query.SetParameter ( "publishDate", DateTime.Now.ToUniversalTime ( ) );

			query.SetMaxResults ( 1000 )
				.SetCacheRegion ( CacheRules.Regions.Tolerant )
				.SetCacheable ( base.UseCache );

			return query.List<Month> ( );
		}

		#endregion
	}
}
